package com.rocksdata.mc.business.location;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.rocksdata.mc.entity.UnreadCache;
import com.ctz.commonframe.utils.SharedPrefrencesUtil;
import com.rocksdata.mc.SharedPreferencesKey;
import com.rocksdata.mc.business.UserInfoManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UnreadManager {
//    private static UnreadManager instance;
//
//    private UnreadManager () {}
//
//    public synchronized static UnreadManager getInstance() {
//        if (instance == null)
//            instance = new UnreadManager();
//        return instance;
//    }
    private static OnReadStatusChangedListener onReadStatusChangedListener;

    public interface OnReadStatusChangedListener {
        void onChanged();
    }

    public static void setOnReadStatusChangedListener (OnReadStatusChangedListener listener) {
        onReadStatusChangedListener = listener;
    }

    public static UnreadCache getUnreadCache () {
        Object unreadObject = SharedPrefrencesUtil.getAboutUser(UserInfoManager.getCurrentUserId(), SharedPreferencesKey.KEY_UNREAD_CACHE, null);
        if (unreadObject != null) {
            return JSON.parseObject((String) unreadObject, UnreadCache.class);
        }
        return null;
    }

    public static void saveUnreadCache (UnreadCache cache) {
        if (cache == null)
            return;
        SharedPrefrencesUtil.putAboutUser(UserInfoManager.getCurrentUserId(), SharedPreferencesKey.KEY_UNREAD_CACHE, JSON.toJSONString(cache));
    }

    public static void setRead (String appId, String code) {
        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(code))
            return;
        UnreadCache cache = getUnreadCache();
        if (cache != null && cache.getUnreadMap() != null) {
            List<String> codeList = cache.getUnreadMap().get(appId);
            if (codeList != null && codeList.size() > 0) {
                codeList.remove(code);
                saveUnreadCache(cache);
            }
        }
        if (onReadStatusChangedListener != null)
            onReadStatusChangedListener.onChanged();
    }

    public static void setUnread (String appId, String code) {
        if (TextUtils.isEmpty(appId) || TextUtils.isEmpty(code))
            return;
        UnreadCache cache = getUnreadCache();
        if (cache == null) {
            cache = new UnreadCache();
        }
        if (cache.getUnreadMap() == null) {
            cache.setUnreadMap(new HashMap<String, List<String>>());
        }
        if (cache.getUnreadMap().get(appId) == null) {
            cache.getUnreadMap().put(appId, new ArrayList<String>());
        }
        cache.getUnreadMap().get(appId).add(code);
        saveUnreadCache(cache);
        if (onReadStatusChangedListener != null)
            onReadStatusChangedListener.onChanged();
    }
}
